#include <REGX52.H>

#define uchar unsigned char  
#define uint unsigned int

sbit LS138_A=P2^2;
sbit LS138_B=P2^3;
sbit LS138_C=P2^4;
sbit LS138_D = P2^5;  

uchar code smgduan[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
                    0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x08};

void delay(unsigned int i);
void HC74LS138(uchar i);
void show(uchar wei,uchar she);
void Timer0Init(void);

unsigned int counter = 0;  
bit flag = 0; 

void main()
{
    Timer0Init();  
    while(1)
    {
        if(flag)  
        {
            flag = 0;  
            counter++; 
            if(counter > 999) 
            {
                counter = 0;
            }
        }

       
       
        show(3, (counter % 1000) / 100);  
        show(2, (counter % 100) / 10);  
        show(1, counter % 10);  
    }
}

void show(uchar wei,uchar she)
{
    P0 = smgduan[she];
    HC74LS138(wei);
    delay(4);
}

void delay(unsigned int i)
{
    unsigned int x,y;
    for(x=0;x<i;x++)
    {
        for(y=0;y<124;y++)
        {
            ;
        }
    }
}

void HC74LS138(uchar i)
{
    switch(i)
    {
        case  1:
        {
            LS138_A = 0;
            LS138_B = 0;
            LS138_C = 0;
            
            break;
        }
        case  2:
        {
            LS138_A = 1;
            LS138_B = 0;
            LS138_C = 0;
            
            break;
        }
        case  3:
        {
            LS138_A = 0;
            LS138_B = 1;
            LS138_C = 0;
            
            break;
        }
        case  4:
        {
            LS138_A = 1;
            LS138_B = 1;
            LS138_C = 0;
           
            break;
        }
        case  5:
        {
            LS138_A = 0;
            LS138_B = 0;
            LS138_C = 1;
           
            break;
        }
        case  6:
        {
            LS138_A = 1;
            LS138_B = 0;
            LS138_C = 1;
            
            break;
        }
        case  7:
        {
            LS138_A = 0;
            LS138_B = 1;
            LS138_C = 1;
            
            break;
        }
        case  8:
        {
            LS138_A = 1;
            LS138_B = 1;
            LS138_C = 1;
            
            break;
        }
  
    }
}

void Timer0Init(void)
{
    TMOD &= 0xF0;  
    TMOD |= 0x01;  
    TH0 = 0xFC;  
    TL0 = 0x18;
    TF0 = 0; 
    TR0 = 1;  
    ET0 = 1;  
    EA = 1;  
    PT0 = 0;  
}

void Timer0_ISR(void) interrupt 1
{
    static unsigned int count = 0;  
    TH0 = 0xFC;  
    TL0 = 0x18;
    count++;
    if(count >= 1000)  
    {
        count = 0;
        flag = 1;  
    }
}